<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>排行榜</title>
    <link rel="icon" th:href="@{/favicon.png}" type="image/png"/>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" th:href="@{/css/Rank.css}">
</head>
<body>
<div id="app">
    <!-- 返回按钮 -->
    <button class="back-button" @click="goToMainPage">返回主页面</button>

    <!-- 排行榜主体 -->
    <div class="leaderboard-container">
        <div class="leaderboard-header">
            <h1 class="leaderboard-title">服务器经营排行榜</h1>
            <p>看看全服服务器管理员们的经营表现</p>
        </div>

        <!-- 排序控制区域 -->
        <div class="sort-controls">
            <div class="sort-options">
                <button
                        v-for="option in sortOptions"
                        :key="option.value"
                        class="sort-btn"
                        :class="{ active: sortField === option.value }"
                        @click="changeSort(option.value)"
                >
                    {{ option.label }}
                </button>
            </div>

            <div>
                <label for="pageSize">每页显示：</label>
                <select id="pageSize" v-model="pageSize" class="page-size-select" @change="fetchRankData">
                    <option value="5">5</option>
                    <option value="10">10</option>
                    <option value="15">15</option>
                </select>
            </div>
        </div>

        <!-- 排行榜表格 -->
        <div v-if="loading" class="loading">加载排行榜数据中...</div>
        <div v-else-if="error" class="error">加载数据失败: {{ error }}</div>
        <template v-else>
            <table class="ranking-table">
                <thead>
                <tr>
                    <th>排名</th>
                    <th>头像</th>
                    <th>用户名</th>
                    <th>总营收</th>
                    <th>行动点消耗</th>
                    <th>最高人流</th>
                    <th>回合数</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(user, index) in rankList" :key="user.userId">
                    <td class="rank-cell" :class="{ 'top-3': user.rank <= 3 }">
                        {{ user.rank }}
                    </td>
                    <td class="avatar-cell">
                        <img
                                v-if="user.headshotUrl"
                                :src="user.headshotUrl"
                                class="user-avatar"
                                alt="用户头像"
                        >
                        <div v-else class="avatar-placeholder"></div>
                    </td>
                    <td>{{ user.username }}</td>
                    <td>{{ formatNumber(user.gold) }}</td>
                    <td>{{ formatNumber(user.actionPoint) }}</td>
                    <td>{{ formatNumber(user.traffic) }}</td>
                    <td>{{ formatNumber(user.turn) }}</td>
                </tr>
                </tbody>
            </table>

            <!-- 分页控件 -->
            <div class="pagination-controls">
                <div class="pagination-buttons">
                    <button
                            class="page-btn"
                            @click="prevPage"
                            :disabled="currentPage === 1"
                    >
                        上一页
                    </button>
                    <button
                            class="page-btn"
                            @click="nextPage"
                            :disabled="currentPage >= totalPage"
                    >
                        下一页
                    </button>
                </div>
                <div class="page-info">
                    第 {{ currentPage }} 页 / 共 {{ totalPage }} 页
                </div>
            </div>
        </template>
    </div>

    <!-- 版权声明 -->
    <footer class="footer">
        Copyright &copy; 2025 Wooming Games. 版权所有。
    </footer>
</div>
<script>
    const { createApp } = Vue

    createApp({
        data() {
            return {
                // 排序选项配置
                sortOptions: [
                    { label: '总营收', value: 'gold' },
                    { label: '行动点', value: 'action_point' },
                    { label: '最高人流', value: 'traffic' },
                    { label: '回合数', value: 'turn' }
                ],
                sortField: 'gold', // 当前排序字段
                rankList: [],      // 排行榜数据
                currentPage: 1,    // 当前页码
                pageSize: 10,      // 每页显示数量
                totalPage: 1,      // 总页数
                loading: false,    // 加载状态
                error: null        // 错误信息
            }
        },
        created() {
            // 组件挂载时获取排行榜数据
            this.fetchRankData();
        },
        methods: {
            // 返回主页面
            goToMainPage() {
                // 实际项目中替换为返回主页面的逻辑
                console.log("返回主页面");
                window.location.href = '/';
            },

            // 更改排序方式
            changeSort(field) {
                if (this.sortField !== field) {
                    this.sortField = field;
                    this.currentPage = 1; // 重置到第一页
                    this.fetchRankData();
                }
            },

            // 获取排行榜数据
            async fetchRankData() {
                this.loading = true;
                this.error = null;

                try {
                    // 获取基础排行榜数据
                    const rankResponse = await axios.post('api/public/rank', {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        orderBy: this.sortField
                    });

                    const pageData = rankResponse.data.data;
                    this.currentPage = pageData.pageNum;
                    this.totalPage = pageData.totalPage;

                    // 获取用户头像
                    this.rankList = await Promise.all(
                        pageData.data.map(async user => {
                            try {
                                const avatarResponse = await axios.get('/api/public/get', {
                                    params: {userId: user.userId},
                                    responseType: 'blob'
                                });

                                return {
                                    ...user,
                                    headshotUrl: URL.createObjectURL(avatarResponse.data)
                                };
                            } catch (error) {
                                console.error(`获取用户 ${user.username} 头像失败:`, error);
                                return {...user, headshotUrl: null};
                            }
                        })
                    );
                } catch (error) {
                    console.error('获取排行榜数据失败:', error);
                    this.error = error.message || '未知错误';
                } finally {
                    this.loading = false;
                }
            },

            // 上一页
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.fetchRankData();
                }
            },

            // 下一页
            nextPage() {
                if (this.currentPage < this.totalPage) {
                    this.currentPage++;
                    this.fetchRankData();
                }
            },

            // 数字格式化
            formatNumber(num) {
                return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
        },
        // 组件销毁时释放头像URL
        beforeDestroy() {
            this.rankList.forEach(user => {
                if (user.headshotUrl) {
                    URL.revokeObjectURL(user.headshotUrl);
                }
            });
        }
    }).mount('#app');
</script>
</body>
</html>